from fastapi import APIRouter, Request, HTTPException, File, UploadFile
from fastapi.responses import StreamingResponse, JSONResponse

from configs import config

from datetime import datetime

from database.database import engine
from sqlalchemy import text

from utils.access_token import create_access_token

import os
import uuid
import hashlib
import json


router = APIRouter(
    prefix='/upload',
    tags = ['文件上传']
)


@router.post("/editor_upload_file")
async def upload_image(file: UploadFile):
    uploadpath = f"upload/{datetime.now().strftime('%Y-%m-%d')}"
    os.makedirs(f"{config.setting.statics.path}/{uploadpath}", exist_ok=True)
    localfile = f"{uuid.uuid4()}.{file.filename.split('.')[-1]}"

    src = f"{config.setting.statics.urls}/{uploadpath}/{localfile}"

    with open(f"{config.setting.statics.path}/{uploadpath}/{localfile}", "wb") as f:
        f.write(file.file.read())

    data = {
        "errorCode": 0, 
        "data": {
            "src": src
        }
    }
    return JSONResponse(status_code=200, content=data)


@router.post("/image")
async def upload_image(file: UploadFile):
    # 检查文件是否为图片
    if not file.content_type.startswith("image/"):
        return {"message": "The uploaded file is not an image."}

    uploadpath = f"images/{datetime.now().strftime('%Y-%m-%d')}"
    os.makedirs(f"{config.setting.statics.path}/{uploadpath}", exist_ok=True)
    localfile = f"{uuid.uuid4()}.{file.filename.split('.')[-1]}"

    src = f"{config.setting.statics.urls}/{uploadpath}/{localfile}"

    with open(f"{config.setting.statics.path}/{uploadpath}/{localfile}", "wb") as f:
        f.write(file.file.read())

    data = { "code": 0, "message": "操作成功", "src":  src}
    return JSONResponse(status_code=200, content=data)
